package com.guyu.plugin.password;


import cn.hutool.core.lang.Pair;
import com.guyu.plugin.password.crypto.PasswordCrypto;
import com.guyu.plugin.password.crypto.impl.SmCrypto;
import com.guyu.plugin.password.exception.PasswordException;

import java.util.Objects;

public abstract class AbstractPassword implements IPassword {
    private static final long serialVersionUID = -4827673764092549630L;

    /**
     * 密码最小长度
     */
    protected int minLength;
    /**
     * 密码最大长度
     */
    protected int maxLength;
    /**
     * 加密算法
     */
    protected PasswordCrypto crypto;

    public AbstractPassword(String publicKeyStr, String privateKeyStr, String salt) {
        this(publicKeyStr, privateKeyStr, salt, 6, 16);
    }

    public AbstractPassword(String publicKeyStr, String privateKeyStr, String salt, int minLength, int maxLength) {
        this(new SmCrypto(publicKeyStr, privateKeyStr, salt), minLength, maxLength);
    }

    public AbstractPassword(PasswordCrypto crypto, int minLength, int maxLength) {
        this.crypto = crypto;
        this.minLength = minLength;
        this.maxLength = maxLength;
    }

    /**
     * 加密规则
     *
     * @param password 明文密码
     * @return 编码为Hex字符串
     */
    protected abstract String encryptRule(String password);

    /**
     * 解密规则
     *
     * @param decryptStr 解密后的密文
     * @return 原始密码
     */
    protected abstract String decryptRule(String decryptStr);

    /**
     * 生成密码
     *
     * @return 原始密码
     */
    protected abstract String createPassword();

    @Override
    public String encrypt(String password) {
        String data = encryptRule(password);
        return crypto.encryptHex(data);
    }

    @Override
    public String decrypt(String encryptPassword) {
        String decryptStr = crypto.decryptStr(encryptPassword);
        return decryptRule(decryptStr);
    }

    @Override
    public String digestHex(String password) {
        return crypto.digestHex(password);
    }

    @Override
    public boolean verify(String encryptPassword, String hexPassword) {
        try {
            String password = decrypt(encryptPassword);
            String hex = digestHex(password);
            return Objects.equals(hex, hexPassword);
        } catch (Exception e) {
            throw new PasswordException("错误的密码");
        }
    }

    @Override
    public Pair<String, String> genPassword() {
        String password = createPassword();
        return genPassword(password);
    }

    @Override
    public Pair<String, String> genPassword(String password) {
        String hex = digestHex(password);
        return Pair.of(password, hex);
    }

}
